package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @RequestMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session){
        R<Employee> r = employeeService.login(employee);
        if (r.getCode()==1){
                session.setAttribute("employee",r.getData().getId());
        }
        return r;
    }

    //退出
    @RequestMapping("/logout")
    public R<String> logout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }

    //添加员工
    @RequestMapping
    public R<String> add(@RequestBody Employee employee,HttpSession session){
        Long id = (Long) session.getAttribute("employee");
        employee.setCreateUser(id);
        employee.setUpdateUser(id);
        employeeService.add(employee);
        return R.success("添加成功");
    }

    //分页条件查询
    @RequestMapping("/page")
    public R<Page<Employee>> findByPage(Integer page,Integer pageSize,String name){
        Page<Employee> pageObj = employeeService.findByPage(page, pageSize, name);
        return R.success(pageObj);
    }

    //修改员工状态
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
        Long id = (Long) session.getAttribute("employee");
        employee.setUpdateUser(id);
        employeeService.update(employee);
        return R.success("修改成功");
    }

    //回显数据
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id){
        Employee emp = employeeService.findById(id);
        return R.success(emp);
    }
}
